import {
  find,
  cancel,
  received,
  reminder,
  payment,
  del,
  temporaryStorage,
  checkOpenBusinessView,
  queryShippingStatus
} from '../../../../api/order';
import {
  submit,
  query
} from '../../../../api/payment';
import {
  buyForOrder
} from '../../../../api/cart';
import {
  create
} from '../../../../api/giftCard.js'
const util = require('../../../../utils/util.js')
let app = getApp();
Page({
  data: {
    img: 'https://icweiliimg1.pstatp.com/weili/l/540018848208912837.webp',
    orderForm: null,
    id: '',
    orderLog: '',
    currentTab: 0,
    payments: [],
    left_time: "00:00",
    timeType: false,
    transferType: false,
    giftNum: 0,
    shippingEmloyeeList: [],
    extractCodeType: false,
    shopName: '',
    shopPhone: '',
    onlinePayment: '',
    extension: true,
    giftCard: app.globalData.giftCard,
    hldelivered: '',
    hldeliveredFlag: true,
    yunchang: app.globalData.yunchang,
    invoiced: app.globalData.invoiced,
    bomType: '',
    costSum:0,
    vipType: app.globalData.userVipType,
    isRead:false
  },
  onLoad: function (options) {
    console.log(options,'订单详情')
    this.data.id = options.id
    if(!util.isNull(options.type)){
      this.data.isRead = true
      console.log(options.type,'订单详情')
    }
    this.setData({
      isRead:this.data.isRead
    })
    this.data.currentTab = options.currentTab
    this.getOnlinePayment(options)
  },
  toPackageDetails() {
    wx.navigateTo({
      url: '/pages/member/logistics/packageDetails?orderid=' + this.data.orderForm.id,
    })
  },
  invoicing() {
    wx.navigateTo({
      url: '/pages/order/jumpPage/order/invoicing?orderForm=' + encodeURIComponent(JSON.stringify(this.data.orderForm)),
    })
  },
  getOnlinePayment(options) {
    this.data.onlinePayment = app.globalData.onlinePayment
    this.data.extension = options.extension
    this.setData({
      onlinePayment: app.globalData.onlinePayment,
      extension: options.extension
    })
  },
  onShow: function () {
    this.findClick(this.data.id)
    wx.onAppShow((options) => {
      if ((options.scene === 1037 || options.scene === 1038) && !util.isNull(options.referrerInfo.extraData)) {
        wx.showLoading({
          title: '查询支付状态',
        })
        const { extraData } = options.referrerInfo
        if (extraData.status == 'success') {
          wx.hideLoading()
          wx.showToast({
            title: '支付成功',
            icon: 'none'
          })
        } else {
          this.data.shippingClickFlag = true //开启防双击
          wx.hideLoading()
          wx.showToast({
            title: '支付失败',
            icon: 'none'
          })
        }
      }
    })
  },
  onUnload: function () {
    clearInterval(this.data.timer);
  },
  cancelClick(data) {
    console.log(data)
    var _this = this
    wx.showModal({
      title: '确认取消订单？',
      content: '取消后可在已关闭订单再次购买',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          _this.loadCancel(data.currentTarget.dataset.id)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  receivedClick() {
    var _this = this
    wx.showLoading({
      title: '加载中'
    })
    checkOpenBusinessView({ orderId: _this.data.id }).then(res => {
      if (!util.isNull(res.data)) {
        wx.hideLoading()
        if (wx.openBusinessView) {
          wx.openBusinessView({
            businessType: 'weappOrderConfirm',
            extraData: {
              merchant_id: res.data.merchant_id,
              merchant_trade_no: res.data.merchant_trade_no,
              transaction_id: res.data.transaction_id
            },
            success() {
              queryShippingStatus({ orderId: _this.data.id }).then(shippingRes => {
                if (shippingRes.data) {
                  received(_this.data.id).then(
                    res => {
                      if (res.type == 'success') {
                        wx.showToast({
                          title: res.content,
                        })
                        _this.findClick(_this.data.id)
                      }
                    }
                  ).catch(error => {
                    console.log(error)
                  })
                }
              })
            },
            fail(err) {
              wx.showToast({
                title: err.errMsg,
                icon: 'none'
              })
            }
          });
        } else {
          wx.showModal({
            title: '提示',
            content: '微信版本过低，请升级',
          })
        }
      } else {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '是否确认收货！',
          success(res) {
            if (res.confirm) {
              received(_this.data.id).then(
                res => {
                  if (res.type == 'success') {
                    wx.showToast({
                      title: res.content,
                    })
                    _this.findClick(_this.data.id)
                  }
                }
              ).catch(error => {
                console.log(error)
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  },
  logisticsClick() {
    wx.navigateTo({
      url: '/pages/member/logistics/list?id=' + this.data.id,
    })
  },
  confirmClick() {
    wx.navigateTo({
      url: '/pages/order/jumpPage/order/confirm',
    })
  },
  evaluationClick() {
    wx.navigateTo({
      url: '/pages/order/jumpPage/order/evaluation?id=' + this.data.id,
    })
  },
  refundClick() {
    wx.navigateTo({
      url: '/pages/order/jumpPage/order/refund',
    })
  },
  datetimeFormatTT(time) {
    let date = new Date(time);
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let hour = date.getHours()
    let minute = date.getMinutes()
    let second = date.getSeconds()
    return month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  },
  GetDateDiff(startTime, endTime, diffType) {
    //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式
    startTime = startTime.replace(/\-/g, "/");
    endTime = endTime.replace(/\-/g, "/");
    //将计算间隔类性字符转换为小写
    diffType = diffType.toLowerCase();
    var sTime = new Date(startTime); //开始时间
    var eTime = new Date(endTime); //结束时间
    //作为除数的数字
    var timeType = 1;
    switch (diffType) {
      case "second":
        timeType = 1000;
        break;
      case "minute":
        timeType = 1000 * 60;
        break;
      case "hour":
        timeType = 1000 * 3600;
        break;
      case "day":
        timeType = 1000 * 3600 * 24;
        break;
      default:
        break;
    }
    return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(timeType));
  },
  timeStamp(second_time) {
    let time = parseInt(second_time) + "秒";
    if (parseInt(second_time) > 60) {
      let second = parseInt(second_time) % 60;
      let min = parseInt(second_time / 60);
      time = min + "分";
      if (min > 60) {
        min = parseInt(second_time / 60) % 60;
        let hour = parseInt(parseInt(second_time / 60) / 60);
        if (min == 0) {
          time = hour + "小时";
        } else {
          time = hour + "小时" + min + "分";
        }
        if (hour > 24) {
          hour = parseInt(parseInt(second_time / 60) / 60) % 24;
          let day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
          time = day + "天" + hour + "小时" + min + "分";
        }
      }
    }
    return time;
  },
  findClick(data) {
    var _this = this
    find(data).then(
      res => {
        if (res.type == 'success') {
          let estimateDate = util.datetimeFormat(res.data.order.estimateDate)  // 86400000 1天 3600000 1小时
          let createDate = util.datetimeFormat(res.data.order.createDate)
          let ECDifference = this.GetDateDiff(createDate, estimateDate, "second")
          if (ECDifference < 86400) {
            this.data.hldelivered = this.timeStamp(ECDifference)
            this.data.hldeliveredFlag = true
            this.setData({
              hldelivered: this.data.hldelivered,
              hldeliveredFlag: this.data.hldeliveredFlag
            })
          } else {
            this.data.hldelivered = this.datetimeFormatTT(estimateDate)
            this.data.hldeliveredFlag = false
            this.setData({
              hldelivered: this.data.hldelivered,
              hldeliveredFlag: this.data.hldeliveredFlag
            })
          }
          if (res.data.order.meta != null) {
            res.data.order.meta = JSON.parse(res.data.order.meta)
          }
          _this.data.orderForm = res.data.order
          _this.data.orderForm.createDate = util.datetimeFormat(_this.data.orderForm.createDate)
          _this.data.orderForm.estimateDate = this.datetimeFormatTT(_this.data.orderForm.estimateDate - 3600000 * 8)
          if (!util.isNull(res.data.orderLog)) {
            res.data.orderLog.forEach(function (item) {
              item.createDate = util.datetimeFormat(item.createDate)
            })
            _this.data.orderLog = res.data.orderLog
          }
          _this.data.orderForm.itemList.forEach(function (item) {
            item.thumbnail = util.thumbnail(item.thumbnail, 170, 170)
          })
          res.data.payments.forEach(item => {
            if (item.attach = ! null) {
              item.attach = JSON.parse(item.attach)
            }

          })
          _this.data.payments = res.data.payments
          if (res.data.order.paymentStatus == 0) {
            _this.countDown(res.data.order.createDate)
          }
          var subShop = []
          var subPlan = []
          res.data.order.itemList.forEach(function (item) {
            if (item.subType == 0) {
              subShop.push(item)
            } else if (item.subType == 1) {
              subPlan.push(item)
            }
          })
          if (subPlan.length > 0) {
            subPlan.forEach(function (item) {
              if (subShop.length > 0) {
                _this.data.giftNum += item.quantity + 1
              } else {
                _this.data.giftNum += item.quantity
              }
            })
          } else {
            _this.data.giftNum = 1
          }
          //计算结算价
          // if (!_this.data.orderForm.cost && _this.data.vipType>1) {
          //   _this.data.orderForm.itemList.forEach(elm=>{
          //     _this.data.costSum += elm.cost*elm.quantity
          //   })
          // }
          _this.data.shippingEmloyeeList = res.data.shippingEmloyeeList
          _this.data.shopName = res.data.shopName
          _this.data.shopPhone = res.data.telephone
          _this.data.bomType = res.data.bomType
          _this.setData({
            orderForm: _this.data.orderForm,
            costSum:_this.data.costSum,
            orderLog: _this.data.orderLog,
            payments: _this.data.payments,
            giftNum: _this.data.giftNum,
            shippingEmloyeeList: _this.data.shippingEmloyeeList,
            shopName: _this.data.shopName,
            shopPhone: _this.data.shopPhone,
            bomType: _this.data.bomType
          })
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },
  loadCancel(data) {
    var _this = this
    console.log(data)
    cancel(data).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          wx.showToast({
            title: res.content,
          })
          _this.findClick(_this.data.id)
        }
      }
    ).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },
  copyClick() {
    wx.setClipboardData({
      data: this.data.orderForm.sn,
      success(res) {
        wx.getClipboardData({
          success(res) {
          }
        })
      }
    })
  },
  invoicedCopyClick() {
    wx.setClipboardData({
      data: this.data.orderForm.meta.billingName + '(' + (this.data.orderForm.meta.billingType == 0 ? '公司' : '个人') + ')' + this.data.orderForm.meta.billingCode,
      success(res) {
        wx.getClipboardData({
          success(res) {
          }
        })
      }
    })
  },
  refundsclick() {
    wx: wx.navigateTo({
      url: '/pages/order/jumpPage/order/refund?id=' + this.data.orderForm.id,
    })
  },
  returnDetailsClick() {
    wx.navigateTo({
      url: '/pages/order/jumpPage/order/refund_details?id=' + this.data.orderForm.id,
    })
  },
  clockClick() {
    var _this = this
    reminder(_this.data.id).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          wx.showToast({
            title: res.content,
          })
        }
      }
    ).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },
  paymentClick(data) { // 付款
    var _this = this
    payment(data.currentTarget.dataset.id).then(res => {
      if (res.type == 'success') {
        console.log(res)
        if (res.data.paymentPluginId == 'facePayPlugin') {
          wx.navigateTo({
            url: '/pages/member/share/determinePage/qRCodePayment?id=' + res.data.id,
          })
        } else {
          if (res.data.way != 2) {
            _this.submitClick(res)
          } else {
            _this.data.sn = res.data.sn
            wx.showLoading({
              title: '等待支付',
            })
            console.log({
              sn: res.data.sn,
              userId: app.globalData.uuid,
              token: app.globalData.token,
              mchName: app.globalData.mchName,
              amount: res.data.amount,
              createDate: res.data.createDate,
              // itemList: data.data.itemList,
              address:  this.data.orderForm.address,
              consignee: this.data.orderForm.consignee,
              phone:  this.data.orderForm.phone,
              memo: res.data.memo,
              firstEnter: true
            });
            wx.openEmbeddedMiniProgram({
              appId: 'wx2d00e086c8d08008',
              path: `pages/payment/payment`,
              // envVersion: 'trial',
              extraData: {
                sn: res.data.sn,
                userId: app.globalData.uuid,
                token: app.globalData.token,
                mchName: app.globalData.mchName,
                amount: res.data.amount,
                createDate: res.data.createDate,
                // itemList: data.data.itemList,
                address:  this.data.orderForm.address,
                consignee: this.data.orderForm.consignee,
                phone:  this.data.orderForm.phone,
                memo: res.data.memo,
                firstEnter: true
              },
              fail: (fail) => {
                wx.hideLoading()
                wx.showModal({
                  title: '支付失败',
                  content: '拉起支付失败，请点击 "允许" 跳转支付',
                  showCancel: false
                })
                this.data.shippingClickFlag = true //开启防双击
              }
            })
          }
        }
      } else {
        wx.showToast({
          icon: "none",
          title: '支付失败',
        })
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },
  submitClick(data) {
    var _this = this
    _this.data.sn = data.data.sn
    wx.showLoading({
      title: '加载中...',
    })
    submit({
      paymentPluginId: 'weixinMiniPayPlugin',
      sn: data.data.sn
    }).then(res => {
      console.log(res)
      wx.hideLoading()
      if (res.type == 'success') {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (red) {
            _this.queryClick()
          },
          'fail': function (red) {
            console.log(red);
          }
        })
      } else {
        wx.showToast({
          icon: "none",
          title: '支付失败',
        })
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },
  queryClick() {
    var _this = this
    query({
      sn: _this.data.sn
    }).then(res => {
      console.log(res)
      if (res.type == 'success') {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1500,
          success: function () {
            setTimeout(function () {
              wx.navigateBack({})
            }, 1500)
          }
        })
      } else {
        wx.navigateBack({})
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },
  again() { // 再次购买
    var _this = this
    console.log(this.data.orderForm)
    var product = this.data.orderForm.itemList[0]
    let data = {}
    data.orderId = product.orderId
    data.uuid = app.globalData.uuid
    buyForOrder(data).then(
      res => {
        if (res.type == 'success') {
          wx.navigateTo({
            url: '/pages/goods/submit/index',
          })
        }
      }
    ).catch(error => {
      wx.showToast({
        title: '服务器开小差了，请重新点击购买',
        icon: 'none',
        duration: 2000
      })
    })
  },
  countDown: function (data) {
    var that = this;
    that.data.timer = setInterval(function () {
      var create_time = data.replace(/-/g, "/");
      // console.log(create_time)
      //计算剩余时间差值
      var leftTime = (new Date(create_time).getTime() + 30 * 60 * 1000) - (new Date().getTime());
      if (leftTime > 0) {
        //计算剩余的分钟
        var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);
        //计算剩余的秒数
        var seconds = parseInt(leftTime / 1000 % 60, 10);
        that.data.left_time = minutes + "分" + seconds + "秒";
        that.data.timeType = false
        that.setData({
          left_time: that.data.left_time,
          timeType: that.data.timeType
        });
      } else {
        //移除超时未支付的订单
        that.data.timeType = true
        that.setData({
          timeType: that.data.timeType
        })
      }
    }, 1000);
  },
  delClick() {
    var _this = this
    wx.showModal({
      title: '提示',
      content: '是否确认删除！',
      success(res) {
        if (res.confirm) {
          del(_this.data.id).then(
            res => {
              if (res.type == 'success') {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          ).catch(error => {
            console.log(error)
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  transferClick() {
    this.data.transferType = !this.data.transferType
    this.setData({
      transferType: this.data.transferType
    })
  },
  transferCancel() {
    this.data.transferType = false
    this.setData({
      transferType: this.data.transferType
    })
  },
  saveTransferClick() {
    var _this = this
    create({
      orderId: _this.data.id
    }).then(res => {
      console.log(res)
      if (res.type == 'success') {
        wx.showToast({
          title: '创建成功',
        })
        _this.findClick(_this.data.id)
        wx.navigateTo({
          url: '/pages/member/giftCard/giftCard',
        })
        this.data.transferType = false
        this.setData({
          transferType: this.data.transferType
        })
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },
  phoneClick(data) {
    console.log(data)
    wx.showModal({
      title: '提示',
      content: '是否确认联系骑手',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          if (data.currentTarget.dataset.mobile) {
            wx.makePhoneCall({
              phoneNumber: data.currentTarget.dataset.mobile // 仅为示例，并非真实的电话号码
            })
          } else {
            wx.showToast({
              icon: "none",
              title: '暂无联系方式',
            })
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  extractCodeClick(data) {
    console.log(data)
    var _this = this
    this.data.extractCodeType = !this.data.extractCodeType
    this.setData({
      extractCodeType: this.data.extractCodeType
    })
    var id = data.currentTarget.dataset.id
    _this.selectComponent("#extract").qrcodeClick(id);
  },
  qrcodeCancelClick() {
    this.data.extractCodeType = !this.data.extractCodeType
    this.setData({
      extractCodeType: this.data.extractCodeType
    })
  },
  toCall() {
    let _this = this
    console.info()
    if (_this.data.shopPhone) {
      wx.makePhoneCall({
        phoneNumber: _this.data.shopPhone // 仅为示例，并非真实的电话号码
      })
    }
  },
  temporaryStorageClick() {
    var _this = this
    let params = {}
    params.orderId = _this.data.id
    wx.showModal({
      title: '提示',
      content: '确认暂存云仓?',
      success(res) {
        if (res.confirm) {
          temporaryStorage(params).then(res => {
            wx.showToast({
              title: '加入成功',
              icon: 'success',
            })
            _this.findClick(_this.data.id)
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
})
